package com.xg.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xg.java.entity.FileShare;
import com.xg.java.service.FileShareService;
import com.xg.java.util.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @description file_share控制器
 * @author wang
 * @date 2021-12-30
 */
@Slf4j
@RestController
@Api(tags = "分享管理")
@RequestMapping("/fileShare")
public class FileShareController {

    @Autowired
    private FileShareService fileShareService;

    @ApiOperation("分享文件或文件夹")
    @PostMapping("/shareFile")
    public Object shareFile(FileShare entity){
        FileShare share = fileShareService.getOne(new LambdaQueryWrapper<FileShare>().eq(FileShare::getShareUser, entity.getShareUser()).eq(FileShare::getFileId, entity.getFileId()));
        if (share!=null){
            return new CommonResult().success(share.getCode());
        }
        entity.setShareTime(new Date());
        // 字符串
        StringBuilder string = new StringBuilder();
        // 循环得到10个字母
        for (int i = 0; i < 4; i++) {
            // 得到随机字母
            char c = (char) ((Math.random() * 26) + 97);
            // 拼接成字符串
            string.append(c);
        }
        entity.setCode(string.toString());
        if (fileShareService.save(entity)) {
            return new CommonResult().success(string.toString());
        }
        return new CommonResult().failed();
    }

    @ApiOperation("提取文件")
    @PostMapping("/extractFile")
    public Object extractFile(Long userId,String code){
        return fileShareService.extractFile(userId,code);
    }

}